import random
import werkzeug
from flask import Blueprint, render_template, request, jsonify, flash, redirect, url_for, abort, Response
from flask_login import current_user

from models.my_model import Post, User, R, UserRo, Comment, Like

page_search = Blueprint("search", __name__)


@page_search.route("/search", methods=["GET", "POST"])
def search():
    pageSize = 5
    keyword = request.args.get("keyword")
    page = request.values.get('page')
    post_like_id_all = []
    try:
        page: int = int(page)
    except Exception as v:
        print(v)
    if not page:
        page = 1
    post_all = Post.query.filter(
        Post.title.ilike(f"%{keyword}%")).order_by(Post.create_time.desc()).paginate(page=page, per_page=pageSize)
    posts_count = post_all.total
    if current_user.is_anonymous == False:
        like_all = Like.query.filter(Like.user_id == current_user.id).all()
        for post_like in like_all:
            post_like_id_all.append(post_like.target_post_id)
    for post in post_all:
        user = User.query.filter(User.id == post.user_id).first()
        post.username = user.username
        post.header_url = user.header_url
    return render_template(
        "search.html",
        keyword=keyword,
        posts_all=post_all,
        posts_count=posts_count,
        post_like_id_all=post_like_id_all,
        pagination=post_all
    )
